package vrp;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.*;

import java.util.List;

import vrp.PMF;
import vrp.Customer;
import vrp.SaleOrder;

public class CustomerDeleteServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
    	
    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	
        long keyid = Integer.parseInt(req.getParameter("key"));
        
        Key key = KeyFactory.createKey(Customer.class.getSimpleName(), keyid);
        Customer customer = pm.getObjectById(Customer.class, key);
        boolean isDepot = customer.getIsDepot();
        String respondRedirect = "";
        if (isDepot == true) {
        	respondRedirect = "/depots.jsp";
        } else {
        	respondRedirect = "/customers.jsp";
        }
        
        //check whether customer has placed any sale order
        //if yes, cannot delete
        Query query = pm.newQuery(SaleOrder.class);
        query.setFilter("customer == customerKeypara");
        query.declareParameters("String customerKeypara");
        List<SaleOrder> saleOrders = (List<SaleOrder>) query.execute(key);
        if (saleOrders.size()!=0) {
        	pm.close();
        	resp.sendRedirect(respondRedirect + "?error=inuse");
        	return;
        }
        
        try {
        	//delete all related distances
        	long customerID = customer.getKey().getId();
        	Query query1 = pm.newQuery(Distance.class);
            query1.setFilter("from == customerIDpara");
            query1.declareParameters("long customerIDpara");
            query1.deletePersistentAll(customerID);
        	Query query2 = pm.newQuery(Distance.class);
            query2.setFilter("to == customerIDpara");
            query2.declareParameters("long customerIDpara");
            query2.deletePersistentAll(customerID);

            //delete the customer
            pm.deletePersistent(customer);
        } finally {
            pm.close();
        }
        resp.sendRedirect(respondRedirect);
    }
}
